import service from '../common/service';
import { rdsRequest,getRdsUrl, refreshToken,rdsRequestAsync } from './rdsServices';
import apps from "@/pages/MainViews/app";

const initRelatedName = async () => {
    const rdsUrl = getRdsUrl();

    let rdsUsers = service.getLocalStorage('rdsUsers');
    if (rdsUsers) return;
    service.enjoyShowLoading('正在加载档案...');
    const result = await rdsRequest(rdsUrl.bcApi, 'Rds公共服务', 'GetAllRelatedName');
    service.addlocalStorage('rdsUsers', result.ds0);
    service.addlocalStorage('rdsDeparts', result.ds1);
    service.addlocalStorage('rdsStores', result.ds2);
    service.addlocalStorage('rdsOrganizes', result.ds3);
    service.addlocalStorage('rdsRegions', result.ds4);
    service.addlocalStorage('rdsGdsclasses', result.ds5);
    service.addlocalStorage('rdsBrands', result.ds6);
    service.addlocalStorage('rdsWnos', result.ds7);
    service.addlocalStorage('rdsPayTypes', result.ds8);
    service.addlocalStorage('rdsProviders', result.ds9);
    service.addlocalStorage('rdsDelivers', result.ds10);
    service.addlocalStorage('rdsPropGroups', result.ds11);
    service.addlocalStorage('rdsStoreGrouts', result.ds12);
    service.addlocalStorage('rdsSettles', result.ds13);
    service.addlocalStorage('rdsCusts', result.ds14);
	service.addlocalStorage('rdsFeeItem', result.ds15);
	service.addlocalStorage('rdsBillType', result.ds16);
	service.addlocalStorage('rdsCounter', result.ds17);
	service.addlocalStorage('rdsDpoint', result.ds18);
	service.addlocalStorage('rdsCombGroup', result.ds19);
	service.addlocalStorage('rdsCombBind', result.ds20);
	service.addlocalStorage('rdsPayCode', result.ds21);
    service.enjoyHideLoading();
};

const initRdsDict = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsDict');
    if (rdsDict) return;
    service.enjoyShowLoading('正在加载字典...');
    const result = await rdsRequest(rdsUrl.mainApi, 'dictionaryservice', 'GetDictionary');
    service.addlocalStorage('rdsDict', result);
    service.enjoyHideLoading();
    initRdsAuditStatusDict();
};


const initRdsAuditStatusDict = async () => {
    let rdsDict = service.getLocalStorage('rdsDict');
    if (rdsDict) return;
    const dictMap = rdsDict?.filter(x => x.s_gl_flag_yn === 's_gl_bill_status');
    service.addlocalStorage('s_gl_bill_status', dictMap);
};

const initConName = async () => {
    const rdsUrl = getRdsUrl();
    // const enableSettle = getSyscfgValue('是否启用结算分区','系统参数') == '1'
    // BC
    const result = await rdsRequestAsync(rdsUrl.bcApi, 'Rds公共服务', 'GetContractRelatedName');
    if (!result.HasException) {
        service.addlocalStorage('rdsDataRule', result.ObjectData.ds0);
        service.addlocalStorage('rdsLateFeeRule', result.ObjectData.ds1);
    }
  }
/**
 * 获取用户字典
 * 不初始化全部用户字典，根据需要进行缓存
 * @param {*} key 'u_pr_chgprice_reason'
 * @returns []
 */
// const getRdsUserDict = async (key) => {
//   let jsonData = service.getLocalStorage(key);
//   if (jsonData) {
//     const result = JSON.parse(jsonData);
//     const data = result.find(x => x.c_class === value);
//     return data || [];
//   };
//   service.enjoyShowLoading('正在加载用户字典...');
//   const result = await rdsRequest(rdsUrl.mainApi, '用户字典定义', 'EnjoyQueryList',
//     {
//       BillId: key,
//       WhereList: [
//         { c_col: "c_status", c_oper: "等于", c_value: '0', c_logic: "而且" },
//       ]
//     });
//     console.log("resul11111111111111",result)
//     if (!result) {
//       return []
//     }
//     service.addlocalStorage(key, [...result.ds1,...result.ds2]);
//     const list = result.find(x => x.c_class === key)
//     return list || [];
// };

const initRdsUserDict = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsUserDict');
    if (rdsDict) return;
    service.enjoyShowLoading('正在加载用户字典...');
    const req = {
        IsNotPage: true,
        WhereList: [
            { c_col: "c_status", c_oper: "等于", c_value: '1', c_logic: "而且" },
        ]
    };
    service.enjoyShowLoading('正在加载字典...');
    const result = await rdsRequest(rdsUrl.mainApi, '用户字典定义', 'EnjoyQueryList', req);
    service.addlocalStorage('rdsUserDict', result.ReturnObject);
    service.enjoyHideLoading();
};


/**
 * 获取系统参数
 * 不初始化系统全部参数，根据需要进行缓存
 * @param {*} value 'u_must_input_pdt_except_adnos'
 * @returns
 */
const getRdsSysConfig = async (key, value) => {
    const rdsUrl = getRdsUrl();

    if (!key || !value) {
        return '';
    }
    let jsonData = service.getLocalStorage(key);
    if (jsonData) {
        // const result = JSON.parse(jsonData);
        const result = jsonData;
        const data = result.find(x => x.c_class === key && x.c_name === value);
        if (data?.c_value != undefined) {
            return data.c_value;
        } else {
            clearRdsLocalStorage(key);
        }
    };
    const result = await rdsRequest(rdsUrl.mainApi, '系统配置维护', 'EnjoyQueryList',
        {
            IsNotPage: true, CurrentPage: 1, PageSize: 100,
            BillType: "",
            WhereList: [
                { c_col: "c_class", c_oper: "等于", c_value: key, c_logic: "而且", c_col_dtype: "System.String" }
            ]
        });
    if (!result.ReturnObject) {
        return ''
    }
    service.addlocalStorage(key, result.ReturnObject);
    const list = result.ReturnObject.find(x => x.c_class === key && x.c_name === value)
	if (list?.c_value != undefined) {
        return list.c_value;
    } else {
        console.log('获取系统参数失败', key, value);
        service.enjoyShowLoading(`获取系统参数[${key}][${value}]失败...`);
        setTimeout(() => {
            service.enjoyHideLoading();
        }, 2000);
    }
};


/**
 *
 * @returns 初始化费用项目
 */
const initRdsFeeItem = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsFeeItem');
    if (rdsDict) return;
    const result = await rdsRequest(rdsUrl.bcApi, '费用项目定义', 'EnjoyQueryList', {
        IsNotPage: true, CurrentPage: 1, PageSize: 100,
        BillType: "",
        WhereList: [
        ]
    });
    service.addlocalStorage('rdsFeeItem', result.ReturnObject);
};


/**
 *
 * @returns 初始化巡检时间段
 */
const initRdsPatrolPeriod = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsPatrolPeriod');
    if (rdsDict) return;
    const result = await rdsRequest(rdsUrl.bcApi, '巡检计划单', 'GetPatrolPeriod', {
        IsNotPage: true, CurrentPage: 1, PageSize: 100,
        BillType: "",
        WhereList: [
        ]
    });
    service.addlocalStorage('rdsPatrolPeriod', result);
};

/**
 *
 * @returns 初始化巡检主题清单
 */
const initRdsPartolSubject = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsPartolSubject');
    if (rdsDict) return;
    const result = await rdsRequest(rdsUrl.bcApi, '巡检主题清单', 'EnjoyQueryList', {
        IsNotPage: true, CurrentPage: 1, PageSize: 100,
        BillType: "",
        WhereList: [
        ]
    });
    service.addlocalStorage('rdsPartolSubject', result.ReturnObject);
}

/**
 *
 * @returns 初始化物业服务类型
 */
const initRdsServiceType = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsServiceType');
    if (rdsDict)
    {
        service.removeStorageSync('rdsServiceType');
        // return
    }
    const result = await rdsRequest(rdsUrl.bcApi, '物业服务类型', 'GetServiceType', "");
    service.addlocalStorage('rdsServiceType', result?.ReturnObject);
};


/**
 *
 * @returns 初始化物业服务项目
 */
const initRdsPServiceItem = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsPServiceItem');
    if (rdsDict)
    {
        service.removeStorageSync('rdsPServiceItem');
        // return
    }
    const result = await rdsRequest(rdsUrl.bcApi, '物业服务项目', 'EnjoyQueryList',
        {
            IsNotPage: true, CurrentPage: 1, PageSize: 100,
            BillType: "",
            WhereList: [
            ]
        }
    );
    service.addlocalStorage('rdsPServiceItem', result?.ReturnObject);
}

/**
 *
 * @returns 初始化采购基地
 */
const initRdsFreshLocation = async () => {
    const rdsUrl = getRdsUrl();

    let rdsDict = service.getLocalStorage('rdsFreshLocation');
    if (rdsDict) return;
    const result = await rdsRequest(rdsUrl.bcApi, '生鲜采购地维护', 'EnjoyQueryList', {
        IsNotPage: true, CurrentPage: 1, PageSize: 100,
        BillType: "",
        WhereList: [
        ]
    });
    service.addlocalStorage('rdsFreshLocation', result.ReturnObject);
};

/**
 * 获取当前用户的部门权限设置
 * @returns {Promise<String[]>}
 */
const getRdsUserDepartAuthority = async (sUser) => {
    const rdsUrl = getRdsUrl();

    let myAdnos = [];
    let rdsUserDepartAuthority = service.getLocalStorage('rdsUserDepartAuthority');
    if (rdsUserDepartAuthority) {
        let rdsUserData = typeof rdsUserDepartAuthority === 'string' ? JSON.parse(rdsUserDepartAuthority) : rdsUserDepartAuthority;
        rdsUserData.forEach(element => {
            myAdnos.push(element.Code)
        });
        return myAdnos;
    }
    let loginInfo = apps.getStorageSync('login_data');
    let user = sUser ? sUser : loginInfo.sUser;
    const result = await rdsRequest(rdsUrl.mainApi, '部门权限设置', 'GetUserDepartAuthority', user);
    service.addlocalStorage('rdsUserDepartAuthority', result);
    result.forEach(element => {
        myAdnos.push(element.Code)
    });
    return myAdnos;
};

/**
 * 重量单位
 * @returns {Promise<String[]>}
 */
const initWeightUnits = async() => {
    const rdsUrl = getRdsUrl();

    let jsonData = service.getLocalStorage("rdsWeightUnits");
    if (jsonData) {
        return;
    };
    const result = await rdsRequest(rdsUrl.bcApi, 'Rds公共服务', 'FetchWeightUnit');
    service.addlocalStorage('rdsWeightUnits', result);
}
/**
 * 清除本地缓存
 * @returns {Promise<void>}
 */
const clearRdsLocalStorage = async (key) => {
    if (key) {
        await service.removeStorageSync(key);
        return;
    };
    await service.removeStorageSync('rdsUsers');
    await service.removeStorageSync('rdsDeparts');
    await service.removeStorageSync('rdsStores');
    await service.removeStorageSync('rdsOrganizes');
    await service.removeStorageSync('rdsRegions');
    await service.removeStorageSync('rdsGdsclasses');
    await service.removeStorageSync('rdsBrands');
    await service.removeStorageSync('rdsWnos');
    await service.removeStorageSync('rdsPayTypes');
    await service.removeStorageSync('rdsProviders');
    await service.removeStorageSync('rdsDelivers');
    await service.removeStorageSync('rdsPropGroups');
    await service.removeStorageSync('rdsStoreGrouts');
    await service.removeStorageSync('rdsSettles');
    await service.removeStorageSync('rdsCusts');
    await service.removeStorageSync('rdsDict');
    await service.removeStorageSync('rdsUserDict');
    await service.removeStorageSync('rdsUserDepartAuthority');
    await service.removeStorageSync('s_gl_bill_status');
    await service.removeStorageSync('进销存管理参数');
    await service.removeStorageSync('供应链管理参数');
    await service.removeStorageSync('单据是否审批');
    await service.removeStorageSync('商品验收控制参数');
	await service.removeStorageSync('rdsWeightUnits');
    // service.clearStorageSync()
};

const init = async () => {
    await refreshToken();
    await initRelatedName();
    await initRdsDict();
    await initRdsUserDict();
    await initRdsFeeItem();
    await initRdsFreshLocation();
	await initWeightUnits();
    await initConName();
}

export {
    init,
    initRelatedName,
    initRdsDict,
    initRdsUserDict,
    initRdsFeeItem,
    initRdsPatrolPeriod,
    initRdsServiceType,
    initRdsFreshLocation,
    getRdsSysConfig,
    getRdsUserDepartAuthority,
    clearRdsLocalStorage,
    initRdsPartolSubject,
    initRdsPServiceItem,
    initWeightUnits,
    initConName
};
